"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/7/9 10:25
@Description :
"""
from bs4 import BeautifulSoup

html = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> 
    <a href="http://example.com/tillie" class="sister" id-"link3">Tillie</a>
</body>   
"""
# 初始化 BeautifulSoup实例  参数1  需要解析的文本   参数2  指定解析器
soup = BeautifulSoup(html, 'lxml')

# 获取title节点
title = soup.title
print(title)
"""
  soup.标签名     只能获取一个节点   优先匹配
"""
a = soup.a
print(a, type(a))
# 获取a标签的内容  tag.string
print('a=', a.string)
# 获取标签属性
dct = a.attrs
print(dct.get('class'))
print(dct.get('id'))
print(dct.get('href'))
print('*' * 20)

# 根据嵌套关系 选择节点
title = soup.head.title
print(title, title.string)

print('*' * 20)
# 通过父节点获取子节点
body = soup.body
childrens = body.contents
print(childrens)

print('*' * 20)
# 获取兄弟节点
next_ele = a.next_sibling  # 获取下一个兄弟节点
print(next_ele)
next_eles = a.next_siblings  # 获取后面的所有兄弟节点
for next in next_eles:
    print(next)

print('*' * 20)
title = soup.title
# 获取父节点
print(title.parent)

html = """
<div class="panel-body">
    <div class="panel-heading">
        <h4>Hello</h4>
    </div>
    <div class="panel-heading" id="div2">
        <h4>Hello word</h4>
    </div>
    <ul class="list" id="list-1">
        <li class="element"> Foo</li>
        <li class="element">Bar</li>
        <li class="element">]ay</li>
    </ul>
    <ul class="list list-small" id="list-2">
        <li class="element"> Foo</li>
        <li class="element">Bar</li>
    </ul
</div>
"""
print('--------------------css选择器实现节点的选择----------------------')
soup = BeautifulSoup(html, 'lxml')
# select  列表
result = soup.select('#div2>h4')
for h in result:
    print(h, type(h))

lis = soup.select('#list-1 li')
print(lis)
